package com.xltt.watchfota.utils;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.text.DecimalFormat;

public class FileUtils {
    private static final int GB = 1024 * 1024 *1024;
    private static final int MB = 1024 * 1024;
    private static final int KB = 1024;
    private static final String UPDATE_PATH = "/data/ota_package"/*Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath()*/;
    /**
     * 通过 ‘？’ 和 ‘/’ 判断文件名
     */
    public static String getUrlFileName(String url) {
        int index = url.lastIndexOf('?');
        String filename;
        if (index > 1) {
            filename = url.substring(url.lastIndexOf('/') + 1, index);
        } else {
            filename = url.substring(url.lastIndexOf('/') + 1);
        }
        return filename;
    }

    /**
     * 下載文件保存路徑
     * @return
     */
    public static String getDownloadFilePath() {
        String path = "";
        if (TextUtils.isEmpty(path)) {
            path = UPDATE_PATH;
        } else {
            File file = new File(path);
            if (!file.exists()) {
                Log.e("zhanghui", "getFilePath: " + "path is null, data is continue");
            } else {
                path = file.getPath();
                Log.e("zhanghui", "getFilePath: next path = " + path);
            }
        }
        Log.d("zhanghui", "保存下载文件 path = " + path);
        return path;
    }

    public static String bytes2kb(double bytes){
        DecimalFormat format = new DecimalFormat("###.00");
        if (bytes / GB >= 1){
            return format.format(bytes / GB) + "GB";
        }
        else if (bytes / MB >= 1){
            return format.format(bytes / MB) + "MB";
        }
        else if (bytes / KB >= 1){
            return format.format(bytes / KB) + "KB";
        }else {
            return bytes + "B";
        }
    }
}
